import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:fate_blind_box/im/groupallperson.dart';
import 'package:fate_blind_box/im/person_info.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/ui/user/Settings/complaint_list_submit_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import '../network/Api.dart';
import '../utils/common_widget.dart';
import 'package:fate_blind_box/routes/page_route_names.dart';
import '../utils/loading.dart';
import '../utils/provider.dart';
import '../utils/snack_bar.dart';
import 'addgroupmember.dart';
import 'checkqr.dart';
import 'group/changegroupname.dart';
import 'package:universal_html/html.dart' as html;

///群主详情 rxl
class GroupDetailsPage extends StatefulWidget {
  String groupId;
  String owner;

  GroupDetailsPage(this.groupId, this.owner, {Key? key}) : super(key: key);

  @override
  _GroupDetailsPageState createState() => _GroupDetailsPageState();
}

class _GroupDetailsPageState extends State<GroupDetailsPage> {
  bool _top = false;
  bool _showName = false;
  bool _contact = false;
  bool _dnd = false;

  String cardName = '默认';
  bool isGroupOwner = false;

  late final List _listData = [
    {'user': '+'},
    // {'user': '-'}
  ];

  late String groupName = "";

  late String datas = "";

  var memberEaseGroup;

  Map ownData = {};

  @override
  void initState() {
    super.initState();

    _getGroupInfo();
    //_getGroupInfo();
    //getCardName();
  }

  // 获取群组信息
  _getGroupInfo() async {
    final easeName = await Provider.getUserEaseName();
    if (kDebugMode) {
      print('rx--环信用户id-------' + Provider.userEaseName);
      print('rx--环信用户id-------' + widget.groupId);
    }
    if (widget.groupId.isEmpty || Provider.userEaseName.isEmpty) return;
    loading(() async {
      final res = await Api.getInstance()
          .getGroupInformation(widget.groupId, Provider.userEaseName);
      var data = res['data'];
      var code = res['code'];
      if (code == 0) {
        if (data != null) {
          datas = res['data']['memberEaseGroup']['groupName'];
          memberEaseGroup = res['data']['memberEaseGroup'];
          if (kDebugMode) {
            print('------获取群成员异常---------------' + datas);
            print('------获取群成员异常---------------' +
                res['data']['memberEaseGroup'].toString());
          }
          List list = data['memberEaseEditDTOS'];
          if (data['memberGroupRelat'] != null) {
            ownData = data['memberGroupRelat'];
          }
          if (list.isNotEmpty == true) {
            setState(() {
              _listData.clear();
              _listData.addAll(list);
              _listData.add({'user': '+'});
              print('xxx ${ownData['isOwner']}');
              //1群主， 0不是
              if (ownData['isOwner'] == 1) {
                _listData.add({'user': '-'});
              }
            });
          }
        } else {
          if (kDebugMode) {
            print('------获取群成员异常---------------' + res['msg']);
          }
        }
      } else {
        toast(res['msg']);
      }
    });
  }

  Widget memberItem(item) {
    List<dynamic> userInfo;
    String uId;
    String uFace = '';
    String nickName;
    print('-------------------' + item.toString());
    if (item['user'] == "+" || item['user'] == '-') {
      return InkWell(
        child: SizedBox(
          width: 60,
          child: Image.asset(
            'images/${item['user']}.png',
            height: 48.0,
            width: 48.0,
          ),
        ),
        onTap: () {
          if (item['user'] == "+") {
            //拉人
            Navigator.of(context).push(MaterialPageRoute(
                builder: (builder) => AddGroupMember(widget.groupId, "", '2')));
          }
        },
      );
    }
    return SizedBox(
      width: 60,
      child: InkWell(
        onTap: () {
          if (item['id'].toString().isEmpty) return;
          Get.to(PersonInfo(sig: item['id'].toString()),
              routeName: PageRouteNames.personInfoPage);
        },
        highlightColor: Colors.transparent,
        child: Column(
          children: <Widget>[
            AppWidget.blurFixImage(
              imgWidth: 50,
              sigmaNum: 1.5,
              sign: 0,
              url: Provider.fixAvatar(
                item['profilePhoto'].toString(),
              ),
            ),
            const SizedBox(height: 2),
            Container(
              alignment: Alignment.center,
              height: 20.0,
              width: 50,
              child: Text(
                item['nickName'].toString(),
                style: const TextStyle(fontSize: 12.0),
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 设置消息免打扰
  _setDND(int type) {
    // DimGroup.setReceiveMessageOptionModel(widget.peer, Data.user(), type,
    //     callback: (_) {});
  }

  // 添加环信用户信息
  _quitGroup(String string) async {
    if (string.isEmpty) return;
    final res = await Api.getInstance().quitGroup(string);
    final data = res['data'];
    if (res["code"] == 0) {
      setState(() {
        Navigator.of(context).pop("1");
        Navigator.of(context).pop("1");
        Navigator.of(context).pop("1");
        ThemeSnackBar.show(context, '退出群聊成功');
      });
    } else {
      if (kDebugMode) {
        print('------获取用户异常---------------' + res['msg']);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return AppWidget.navTitleBar(
      bgColor: Colors.white,
      title: datas.isNotEmpty ? datas : "",
      childWidget: ScrollConfiguration(
        behavior: CusBehavior(),
        child: ListView(
          children: <Widget>[
            Container(
              color: Colors.white,
              padding: const EdgeInsets.only(top: 10.0, bottom: 10),
              child: Wrap(
                runSpacing: 20.0,
                spacing: 10,
                children: _listData.map(memberItem).toList(),
              ),
            ),
            Visibility(
              visible: true,
              child: MaterialButton(
                padding: const EdgeInsets.only(top: 15.0, bottom: 20.0),
                color: Colors.white,
                child: const Text(
                  '查看全部群成员',
                  style: TextStyle(fontSize: 16.0, color: Colors.black54),
                ),
                onPressed: () {
                  Navigator.of(context).push(MaterialPageRoute(
                      builder: (builder) => GroupAllPersonPage(
                            widget.groupId,
                          )));
                },
              ),
            ),
            const SizedBox(height: 10.0),
            functionBtn(
              '群聊名称',
              detail: datas.toString().length > 7
                  ? '${datas.toString().substring(0, 6)}...'
                  : datas.toString(),
              right: Container(),
            ),
            ownData['isOwner'] == 1
                ? functionBtn(
                    '群头像',
                    detail: "",
                    right: memberEaseGroup != null
                        ? CachedNetworkImage(
                            imageUrl:
                                Provider.fixAvatar(memberEaseGroup['groupUrl']),
                            width: 24,
                            height: 24,
                          )
                        : Container(),
                  )
                : SizedBox(),
            functionBtn(
              '群二维码',
              right: Image.asset('images/group_code.png', width: 20),
              detail: '',
            ),
            // functionBtn(
            //   '群公告',
            //   detail: "",
            //   right: Container(),
            // ),
            Visibility(
              visible: isGroupOwner,
              child: functionBtn('群管理', detail: '', right: Container()),
            ),
            // functionBtn('备注', detail: '', right: Container()),
            // // const SizedBox(height: 10.0),
            // functionBtn('查找聊天记录', detail: '', right: Container()),
            // const SizedBox(height: 10.0),
            // functionBtn('消息免打扰',
            //     right: CupertinoSwitch(
            //       value: _dnd,
            //       onChanged: (bool value) {
            //         _dnd = value;
            //         setState(() {});
            //         value ? _setDND(1) : _setDND(2);
            //       },
            //     ),
            //     detail: ''),
            // functionBtn('聊天置顶',
            //     right: CupertinoSwitch(
            //       value: _top,
            //       onChanged: (bool value) {
            //         _top = value;
            //         setState(() {});
            //         value ? _setTop(1) : _setTop(2);
            //       },
            //     ),
            //     detail: ''),
            // functionBtn('保存到通讯录',
            //     right: CupertinoSwitch(
            //       value: _contact,
            //       onChanged: (bool value) {
            //         _contact = value;
            //         setState(() {});
            //         value ? _setTop(1) : _setTop(2);
            //       },
            //     ),
            //     detail: ''),
            // //  const SizedBox(height: 10.0),
            // // functionBtn('我在群里的昵称', detail: cardName, right: Container()),
            // functionBtn('显示群成员昵称',
            //     right: CupertinoSwitch(
            //       value: _showName,
            //       onChanged: (bool value) {
            //         _showName = value;
            //         setState(() {});
            //         value ? _setTop(1) : _setTop(2);
            //       },
            //     ),
            //     detail: ''),
            // // const SizedBox(width: 10,),
            // functionBtn('设置当前聊天背景', detail: '', right: Container()),
            // functionBtn('投诉', detail: '', right: Container()),
            //const SizedBox(width: 10,),
            // functionBtn('清空聊天记录', detail: '', right: Container()),
            // const SizedBox(width: 10,),
            MaterialButton(
              padding: const EdgeInsets.symmetric(vertical: 15.0),
              color: Colors.white,
              onPressed: () {
                // if (widget.owner == '') return;
                if (memberEaseGroup['groupId'].toString().isEmpty) return;
                _versionOfdown(context, '确定删除本群吗？');
                // confirmAlert(context, (isOK) {
                //   if (isOK) {
                //     // DimGroup.quitGroupModel(widget.peer, callback: (str) {
                //     //   if (str.toString().contains('失败')) {
                //     //     print('失败了，开始执行解散');
                //     //     DimGroup.deleteGroupModel(widget.peer,
                //     //         callback: (data) {
                //     //           if (str.toString().contains('成功')) {
                //     //             Navigator.of(context).pop();
                //     //             Navigator.of(context).pop();
                //     //             if (Navigator.canPop(context)) {
                //     //               Navigator.of(context).pop();
                //     //             }
                //     //             print('解散群聊成功');
                //     //             showToast(context, '解散群聊成功');
                //     //           }
                //     //         });
                //     //   } else if (str.toString().contains('succ')) {
                //     //     Navigator.of(context).pop();
                //     //     Navigator.of(context).pop();
                //     //     if (Navigator.canPop(context)) {
                //     //       Navigator.of(context).pop();
                //     //     }
                //     //     print('退出成功');
                //     //     showToast(context, '退出成功');
                //     //   }
                //     // });
                //   }
                // },
                //     tips: '确定要退出本群吗？',
                //     okBtn: '',
                //     cancelBtn: '',
                //     okBtnStyle: const TextStyle(),
                //     style: const TextStyle(),
                //     warmStr: '');
              },
              child: const Text(
                '删除并退出',
                style: TextStyle(
                    color: Colors.red,
                    fontWeight: FontWeight.w500,
                    fontSize: 18.0),
              ),
            ),
            const SizedBox(height: 30.0),
          ],
        ),
      ),
    );
  }

  Future<void> _versionOfdown(context, String title) async {
    showCupertinoDialog(
        context: context,
        builder: (context) {
          return CupertinoAlertDialog(
            title: Text(title),
            actions: <Widget>[
              CupertinoDialogAction(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: const Text(
                  '取消',
                  style: TextStyle(fontSize: 16, color: Colors.black),
                ),
              ),
              CupertinoDialogAction(
                onPressed: () {
                  _quitGroup(memberEaseGroup['groupId'].toString());
                },
                child: Text(
                  '确定',
                  style: TextStyle(fontSize: 16, color: ThemeColor.appColor),
                ),
              ),
            ],
          );
        });
  }

  handle(String title) {
    switch (title) {
      case '备注':
        break;
      case '群聊名称':
        if (memberEaseGroup.toString().isNotEmpty) {
          Navigator.of(context)
              .push(MaterialPageRoute(
                  builder: (builder) => ChangeGroupName(memberEaseGroup)))
              .then((value) => {
                    if (value.toString().isNotEmpty)
                      {
                        //刷新
                        _getGroupInfo(),
                      }
                  });
        }

        break;
      case '群二维码':
        Navigator.of(context).push(
            MaterialPageRoute(builder: (builder) => CheckQr(memberEaseGroup)));
        break;
      case '群公告':
        break;
      case '查找聊天记录':
        // routePush(new SearchPage());
        break;
      case '消息免打扰':
        _dnd = !_dnd;
        _dnd ? _setDND(1) : _setDND(2);
        break;
      case '聊天置顶':
        _top = !_top;
        setState(() {});
        _top ? _setTop(1) : _setTop(2);
        break;
      case '设置当前聊天背景':
        // routePush(new ChatBackgroundPage());
        break;
      case '我在群里的昵称':
        break;
      case '投诉':
        Get.to(const ComplaintListSubmitPage());
        break;
      case '清空聊天记录':
        break;
      case '群头像':
        print('vvvv');
        _checkAvatar();
        break;
    }
  }

  /// 头像
  _checkAvatar() {
    if (!kIsWeb) {
      loading(() async {
        final picker = ImagePicker();
        final pickerFile = await picker.pickImage(source: ImageSource.gallery);
        if (pickerFile != null) {
          CroppedFile? croppedImage = await ImageCropper().cropImage(
              sourcePath: pickerFile.path, //图片资源
              aspectRatio: const CropAspectRatio(ratioX: 1, ratioY: 1), //裁剪框比例
              uiSettings: [
                AndroidUiSettings(
                    toolbarTitle: '裁剪', lockAspectRatio: true //锁定图片纵横比
                    ),
                IOSUiSettings(
                    title: '裁剪',
                    resetButtonHidden: true,
                    //不显示重置按钮
                    aspectRatioLockEnabled: true,
                    //锁定图片纵横比
                    aspectRatioPickerButtonHidden: true,
                    //隐藏切换纵横比按钮
                    doneButtonTitle: "完成",
                    //confirm按钮文字
                    cancelButtonTitle: "取消" //cancel按钮文字
                    )
              ]); //根据XFile对象的路径获得图片进行裁剪
          //裁剪完成

          print('xxxx ${croppedImage?.path} ${Provider.memberId}');
          if (croppedImage != null) {
            //裁剪后图片的路径
            String filepath = croppedImage.path;
            final res = await Api.getInstance().uploadAvatarOfGroup(
                widget.groupId, filepath); //pickerFile.path
            print('zzzz $res');
            if (res['code'] == 0) {
              setState(() {
                ThemeSnackBar.show(context, res['msg']);
                memberEaseGroup['groupUrl'] = res['data']['url'];
              });
            } else {
              ThemeSnackBar.show(context, res['msg']);
            }
            print("filepath-----$filepath");
          }
        }
        // if (pickerFile != null) {
        //   final res = await Api.getInstance().uploadAvatarOfGroup(widget.groupId, pickerFile.path);
        //   if (res['code'] == 0) {
        //     setState(() {
        //       memberEaseGroup['groupUrl'] = res['data']['url'];
        //     });
        //   } else {
        //     ThemeSnackBar.show(context, res['msg']);
        //   }
        // }
      });
    } else {
      final uploadInputElement = html.FileUploadInputElement();
      uploadInputElement.multiple = false;
      uploadInputElement.draggable = true;
      uploadInputElement.click();
      uploadInputElement.onChange.listen((event) {
        final file = uploadInputElement.files?.first;
        if (file != null) {
          loading(() async {
            final formData = html.FormData();
            formData.appendBlob("avatarfile", file.slice(), file.name);
            formData.append("memberId", Provider.memberId);
            Api.getInstance().uploadAvatarFromHtml(formData, (e) {
              if (e['code'] == 0) {
                setState(() {
                  memberEaseGroup['groupUrl'] = e['data']['url'];
                });
              } else {
                ThemeSnackBar.show(context, e['msg']);
              }
            });
          });
        }
      });
    }
  }

  _setTop(int i) {}

  functionBtn(
    title, {
    required final String detail,
    required final Widget right,
  }) {
    return GroupItem(
      detail: detail,
      title: title,
      right: right,
      onPressed: () => handle(title),
    );
  }
}

class CusBehavior extends ScrollBehavior {
  @override
  Widget buildViewportChrome(
      BuildContext context, Widget child, AxisDirection axisDirection) {
    if (Platform.isAndroid || Platform.isFuchsia) return child;
    return buildViewportChrome(context, child, axisDirection);
  }
}

class GroupItem extends StatelessWidget {
  final String detail;
  final String title;
  final VoidCallback onPressed;
  final Widget right;

  const GroupItem({
    Key? key,
    required this.detail,
    required this.title,
    required this.onPressed,
    required this.right,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    if (detail == null && detail == '') {
      return Container();
    }
    double? widthT() {
      if (detail == null) {
        return null;
      } else {
        return detail.length > 35 ? 60 : null;
      }
    }

    bool isSwitch = title == '消息免打扰' ||
        title == '聊天置顶' ||
        title == '保存到通讯录' ||
        title == '显示群成员昵称';
    bool noBorder = title == '备注' ||
        title == '查找聊天记录' ||
        title == '保存到通讯录' ||
        title == '显示群成员昵称' ||
        title == '投诉' ||
        title == '清空聊天记录';

    return MaterialButton(
      padding: const EdgeInsets.only(left: 15, right: 15.0),
      color: Colors.white,
      onPressed: () => onPressed(),
      child: Container(
        padding: EdgeInsets.only(
          top: isSwitch ? 10 : 15.0,
          bottom: isSwitch ? 10 : 15.0,
        ),
        decoration: BoxDecoration(
          border: noBorder
              ? const Border(bottom: BorderSide(color: Colors.grey, width: 0.1))
              : const Border(
                  bottom: BorderSide(color: Colors.grey, width: 0.5)),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Row(
              children: <Widget>[
                Expanded(
                  child: Text(
                    title,
                    style: const TextStyle(color: Colors.black, fontSize: 16.0),
                  ),
                ),
                Visibility(
                  visible: title != '群公告',
                  child: SizedBox(
                    width: widthT(),
                    child: Text(
                      detail ?? '',
                      overflow: TextOverflow.ellipsis,
                      style: const TextStyle(color: Colors.grey),
                    ),
                  ),
                ),
                right ?? Container(),
                const SizedBox(width: 10.0),
                isSwitch
                    ? Container()
                    : Image.asset(
                        'images/ic_right.png',
                        width: 15,
                      ),
              ],
            ),
            Visibility(
              visible: title == '群公告',
              child: Padding(
                padding: const EdgeInsets.symmetric(vertical: 3),
                child: Text(
                  detail ?? '',
                  style: const TextStyle(color: Colors.grey),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}
